package com.rex.saas.mqtt;

import com.rex.saas.utils.MacAddressUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * 项目启动 订阅主题
 *
 * @author zhusiyu
 */
@Slf4j
@Component
@Getter
public class MqttManager implements ApplicationRunner {

    @Resource
    private ListenerCallback callback;

    @Resource
    private MqttConnect mqttConnect;

    @Value("${mqtt.clientId}")
    private String clientId;

    @Value("${mqtt.username}")
    private String userName;

    @Value("${mqtt.password}")
    private String password;

    @Override
    public void run(ApplicationArguments args) {
        String macAddress = MacAddressUtil.getMacAddress();
        if (StringUtils.isEmpty(clientId)){
            clientId = "GW_"+macAddress;
        }
        if (StringUtils.isEmpty(userName)){
            userName = macAddress;
        }
        if (StringUtils.isEmpty(password)){
            password = macAddress;
        }
        try {
            mqttConnect.setMqttClient("GW_"+macAddress, userName, password, callback);
            mqttConnect.sub("/paas/"+macAddress+"/down");
        } catch (Exception e) {
            log.error("MQTT启动连接失败！macAddress:{}", macAddress, e);
        }
    }
}
